/* eslint-disable @typescript-eslint/no-empty-interface */

export type NodeResultItem = {
  endTime: number;
  errorMsg: null;
  execId: string;
  execParams: any[];
  execResult: {
    inputParams: {
      startTime: string;
      _has_result: boolean;
      [key: string]: any;
    };
    results: any[];
  }[];
  execStatus: 'INIT' | 'WAITING' | 'RUNNING' | 'FAILED' | 'FINISHED' | 'INTERRUPT';
  flowId: string;
  nodeId: string;
  nodeType: string;
  outputVars: null;
  parentId: string;
  startTime: number;
  success: boolean;
};

export type EdgeResultItem = {
  edgeId: string;
  execId: string;
  execParams: string;
  flowId: string;
  pass: boolean;
};

export type ResultItem = NodeResultItem & EdgeResultItem;

const isExecutingAtom = atom<boolean>({
  key: 'isExecuting',
  default: false
});

const resultsOfListAtom = atom<ResultItem[]>({
  key: 'resultsOfList',
  default: []
});

export const useNodeResults = () => {
  const [isExecuting, setIsExecuting] = useRecoilState(isExecutingAtom);
  const [resultsOfList, setResultsOfList] = useRecoilState(resultsOfListAtom);

  const addResults = (result: ResultItem) => {
    setResultsOfList((prev) => {
      const list = prev.filter((item) => {
        if (result.nodeId) {
          return item.nodeId !== result.nodeId;
        } else if (result.edgeId) {
          return item.edgeId !== result.edgeId;
        }
        return true;
      });
      console.log([...list, result]);
      return [...list, result];
    });
  };

  const clearResults = () => {
    setResultsOfList([]);
    setIsExecuting(false);
  };

  const hasExecResult = resultsOfList.length > 0;

  return {
    isExecuting,
    hasExecResult,
    setIsExecuting,
    resultsOfList,
    setResultsOfList,
    addResults,
    clearResults
  };
};
